package netty.rpc.framework.core.netty.registry.impl;

import netty.rpc.framework.core.netty.loadbalance.LoadBalance;
import netty.rpc.framework.core.netty.loadbalance.impl.RandomLoadBalance;
import netty.rpc.framework.core.netty.registry.ServiceDiscovery;
import netty.rpc.framework.core.netty.registry.ZKUtils;
import org.apache.curator.framework.CuratorFramework;
import org.springframework.util.StringUtils;

import java.net.InetSocketAddress;
import java.util.List;

/**
 * @author guiyiqiao
 * @date 2020/12/10
 */
public class ZKServiceDiscoveryImpl implements ServiceDiscovery {

    private CuratorFramework zkClient ;

    private LoadBalance loadBalance = new RandomLoadBalance();

    @Override
    public InetSocketAddress lookupService(String serviceName) {
        if(StringUtils.isEmpty(serviceName)){
            return null;
        }
        zkClient = ZKUtils.getZkClient();

        List<String> serviceUrls = ZKUtils.getChildrenNodes(zkClient,serviceName);
        if(serviceUrls.size() == 0){
            throw new RuntimeException("找不到可用服务");
        }
        String serviceUrl = loadBalance.selectServiceAddress(serviceUrls);
        String[] split = serviceUrl.split(":");
        return new InetSocketAddress(split[0],Integer.parseInt(split[1]));
    }
}
